const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const authController = require('../controllers/authController');
const authMiddleware = require('../middleware/authMiddleware');

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../../uploads/avatars'));
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    const filename = `avatar_${req.user.user_id}_${Date.now()}${ext}`;
    cb(null, filename);
  }
});
const upload = multer({ storage });

// 上传头像
router.post('/avatar', authMiddleware, upload.single('avatar'), authController.uploadAvatar);

// 用户注册
router.post('/register', authController.register);

// 用户登录
router.post('/login', authController.login);

// 验证token有效性
router.post('/validate', authController.validateToken);

// 获取当前用户信息
router.get('/profile', authMiddleware, authController.profile);

// 修改基础信息
router.post('/update', authMiddleware, authController.updateProfile);

// 我的收藏
router.get('/favorites', authMiddleware, authController.favorites);

// 旧版浏览历史API（不支持筛选排序）
router.get('/history', authMiddleware, authController.history);

// 新版浏览历史API（支持筛选排序）
router.get('/browse-history', authMiddleware, authController.getBrowseHistory);
router.post('/browse-history', authMiddleware, authController.addBrowseHistory);

// 用户登出
router.post('/logout', authMiddleware, authController.logout);

// 地址管理
// 获取地址列表
router.get('/addresses', authMiddleware, authController.getAddresses);
// 添加新地址
router.post('/addresses', authMiddleware, authController.addAddress);
// 更新地址
router.put('/addresses/:address_id', authMiddleware, authController.updateAddress);
// 删除地址
router.delete('/addresses/:address_id', authMiddleware, authController.deleteAddress);
// 设置默认地址
router.post('/addresses/:address_id/default', authMiddleware, authController.setDefaultAddress);

module.exports = router;